package splug.cjk;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import splug.cjk.packet.BBSCommentPacket;
import splug.cjk.packet.FriendPacket;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class BBSCarPoolTab2Content extends ListActivity {

	private int number;
	private String id;
	private String author;
	private String start;
	private String finish;
	private String time;
	private String content;
	private String date;
	private ArrayList<Content> comment = new ArrayList<Content>();
	private ContentAdapter m_adapter;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bbs_carpool_tab1_content);
		setTitle("카풀 게시물 내용");

		Bundle b = getIntent().getExtras();
		number = b.getInt("NUMBER");
		id = b.getString("ID");
		author = b.getString("AUTHOR");
		start = b.getString("START");
		finish = b.getString("FINISH");
		time = b.getString("TIME");
		content = b.getString("CONTENT");
		date = b.getString("DATE");

		TextView txt_start = (TextView) findViewById(R.id.text_bbs_carpool_tab1_start);
		TextView txt_finish = (TextView) findViewById(R.id.text_bbs_carpool_tab1_finish);
		TextView txt_time = (TextView) findViewById(R.id.text_bbs_carpool_tab1_time);
		TextView txt_content = (TextView) findViewById(R.id.text_bbs_carpool_tab1_content);
		TextView txt_date = (TextView) findViewById(R.id.text_bbs_carpool_tab1_date);
		Button btn_comment = (Button) findViewById(R.id.btn_bbs_carpool_content_comment);
		Button btn_add = (Button) findViewById(R.id.btn_bbs_carpool_content_addfriend);
		Button btn_info = (Button) findViewById(R.id.btn_bbs_carpool_content_info);
		Button btn_report = (Button) findViewById(R.id.btn_bbs_carpool_content_report);

		txt_start.setText(start);
		txt_finish.setText(finish);
		txt_time.setText(time);
		txt_content.setText(content);
		txt_date.setText(date);
		
		//댓글달기 버튼 이벤트
		btn_comment.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(BBSCarPoolTab2Content.this, BBSComment.class);
				startActivityForResult(intent, 1);
			}
		});
		
		//친구추가 버튼 이벤트 추가
		btn_add.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//내 아이디가 친구요청 아이디와 같으면 예외처리 한다
				if(id.equals(author)){
					Toast.makeText(BBSCarPoolTab2Content.this, "자기 자신에게 친구 요청을 할 수 없습니다", Toast.LENGTH_SHORT).show();
				}

				//친구 요청 패킷을 보낸다
				else{
					try {
						Socket socket = new Socket(LetsGoActivity.server_ip, 2007);

						InputStream is = socket.getInputStream();
						OutputStream os = socket.getOutputStream();

						OutputStreamWriter osw = new OutputStreamWriter(os);
						InputStreamReader isr = new InputStreamReader(is);

						osw.write(16);
						osw.flush();

						int ack = isr.read(); 

						if(ack == '1'){
							FriendPacket packet = new FriendPacket(null, id, author);
							ObjectOutputStream output = new ObjectOutputStream(os);
							output.writeObject(packet);

							ack = isr.read();

							if(ack == '1'){

								Toast.makeText(BBSCarPoolTab2Content.this, "친구 요청 완료!", Toast.LENGTH_SHORT).show();
								finish();
							}
							else if(ack == '0'){
								Toast.makeText(BBSCarPoolTab2Content.this, "해당하는 회원을 찾을 수 없습니다", Toast.LENGTH_SHORT).show();
							}
							else if(ack == '2'){
								Toast.makeText(BBSCarPoolTab2Content.this, "이미 친구 요청을 하였습니다", Toast.LENGTH_SHORT).show();
							}
						}
						else{
							Toast.makeText(BBSCarPoolTab2Content.this, "네트워크 연결상대가 좋지 않습니다", Toast.LENGTH_SHORT).show();
							finish();
						}


					} catch (Exception e) {
						Toast.makeText(BBSCarPoolTab2Content.this, "네트워크 연결상대가 좋지 않습니다", Toast.LENGTH_SHORT).show();
						finish();
					}
				}
			}
		});

		//글쓴이 정보보기 버튼 이벤트 추가
		btn_info.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//정보보기 액티비티를 생성한다
				Intent intent = new Intent(BBSCarPoolTab2Content.this, PersonInfo.class);
				Bundle b = new Bundle();
				b.putString("ID", author);
				intent.putExtras(b);
				startActivity(intent);
			}
		});

		//신고하기 버튼 이벤트 추가
		btn_report.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//새로운 액티비티를 생성한다
				Intent intent = new Intent(BBSCarPoolTab2Content.this, ReportSimple.class);
				Bundle b = new Bundle();
				b.putString("ID", id);
				b.putString("AUTHOR", author);
				intent.putExtras(b);
				startActivity(intent);
			}
		});

		try {
			Socket socket = new Socket(LetsGoActivity.server_ip, 2007);
			
			InputStream is = socket.getInputStream();
			OutputStream os = socket.getOutputStream();
			
			OutputStreamWriter osw = new OutputStreamWriter(os);
			InputStreamReader isr = new InputStreamReader(is);
			
			osw.write(11);
			osw.flush();
			
			int ack = isr.read();
			
			if(ack == '1'){
				osw.write(number);
				osw.flush();
				
				ObjectInputStream ois = new ObjectInputStream(is);
				BBSCommentPacket packet = (BBSCommentPacket) ois.readObject();
				comment = packet.getContent();
			}
			else{
				Toast.makeText(BBSCarPoolTab2Content.this, "네트워크 연결상대가 좋지 않습니다", Toast.LENGTH_SHORT).show();
			}
			
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		m_adapter = new ContentAdapter(BBSCarPoolTab2Content.this, R.layout.comment_property, comment);
		setListAdapter(m_adapter);
	}

	//////////////////////이너클래스 시작
	private class ContentAdapter extends ArrayAdapter<Content> {

		private ArrayList<Content> items;

		public ContentAdapter(Context context, int textViewResourceId, ArrayList<Content> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.comment_property, null);
			}
			Content p = items.get(position);
			if (p != null) {
				TextView tt = (TextView) v.findViewById(R.id.toptext);
				TextView bt = (TextView) v.findViewById(R.id.bottomtext);
				if (tt != null){
					tt.setText(p.getTitle());
				}
				if(bt != null){
					bt.setText(p.getId() + "님 께서 댓글을 남기셨습니다.");
				}
			}
			return v;
		}
	}

	//////////////////////이너클래스 끝


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(resultCode == RESULT_OK){
			if(requestCode == 1){
				String str = data.getStringExtra("COMMENT");
				
				try {
					Socket socket = new Socket(LetsGoActivity.server_ip, 2007);
					InputStream is = socket.getInputStream();
					OutputStream os = socket.getOutputStream();
					InputStreamReader isr = new InputStreamReader(is);
					OutputStreamWriter osw = new OutputStreamWriter(os);
					
					osw.write(12);
					osw.flush();
					
					int ack = isr.read();
					
					if(ack == '1'){
						BBSCommentPacket packet = new BBSCommentPacket(null, number, id, str);
						ObjectOutputStream output = new ObjectOutputStream(os);
						output.writeObject(packet);
						
						ack = isr.read();
						
						if(ack == '1'){
							Toast.makeText(BBSCarPoolTab2Content.this, "글쓰기 완료!", Toast.LENGTH_SHORT).show();
						}
						else{
							Toast.makeText(BBSCarPoolTab2Content.this, "네트워크 상태가 불안정합니다", Toast.LENGTH_SHORT).show();
						}
						
					}
					else{
						Toast.makeText(BBSCarPoolTab2Content.this, "네트워크 상태가 불안정합니다", Toast.LENGTH_SHORT).show();
					}
					
					
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				

				try {
					Socket socket = new Socket(LetsGoActivity.server_ip, 2007);
					
					InputStream is = socket.getInputStream();
					OutputStream os = socket.getOutputStream();
					
					OutputStreamWriter osw = new OutputStreamWriter(os);
					InputStreamReader isr = new InputStreamReader(is);
					
					osw.write(11);
					osw.flush();
					
					int ack = isr.read();
					
					if(ack == '1'){
						osw.write(number);
						osw.flush();
						
						ObjectInputStream ois = new ObjectInputStream(is);
						BBSCommentPacket packet = (BBSCommentPacket) ois.readObject();
						comment = packet.getContent();
					}
					else{
						Toast.makeText(BBSCarPoolTab2Content.this, "네트워크 연결상대가 좋지 않습니다", Toast.LENGTH_SHORT).show();
					}
					
					
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				
				m_adapter = new ContentAdapter(BBSCarPoolTab2Content.this, R.layout.comment_property, comment);
				setListAdapter(m_adapter);
				m_adapter.notifyDataSetChanged();
			}
		}
	}

}
